﻿/*
 * 作者与对应接口的作者相同
 */
using SQLite;
using mini_project.Library.Model;
namespace mini_project.Library.Service.impl;

public class ItemService : IItemService {
    // 数据库文件名
    public const string DbName = "todo.sqlite";

    // 数据库文件路径
    public static readonly string DbPath =
        Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData), DbName);

    // 数据库链接
    private static SQLiteAsyncConnection? _connection;

    // 初始化数据库链接
    public static SQLiteAsyncConnection Connection =>
        _connection ??= new SQLiteAsyncConnection(DbPath);


    public async Task<int> UpdateContent(int id, string content) {
        var sql = $"update todoItem set content = '{content}' where id = {id}";
        return await Connection.ExecuteAsync(sql);
    }

    public async Task<int> UpdateIntAttr(int id, string attr, int value) {
        var sql = $"update todoItem set {attr} = {value} where id = {id}";
        return await Connection.ExecuteAsync(sql);
    }

    public async Task<int> DeleteTable() {
        return await Connection.DropTableAsync<Item>();
    }

    public async Task<int> InitTable() {
        // 删除表，不需要返回值
        await DeleteTable();
        // 创建表
        var createTable = await CreateTable();
        if (createTable == -1) {
            return -1;
        }

        // 插入初始化数据
        var item1 = new Item() { Content = "初始化测试项目1", IsDeleted = 0, Status = 0 };
        var item2 = new Item() { Content = "初始化测试项目2", IsDeleted = 0, Status = 1 };
        var item3 = new Item() { Content = "初始化测试项目3", IsDeleted = 0, Status = 0 };

        var list = new List<Item> { item1, item2, item3 };
        await InsertAll(list);
        return 1;
    }

    public async Task<int> CreateTable()
    {
        // 检查表是否存在
        var tableInfo = await Connection.GetTableInfoAsync("todoItem");
        // 如果获取到表的数据，说明表已存在，无需创建（表不存在时，tableInfo长度为0）
        if (tableInfo != null && tableInfo.Count != 0) return 0;
        // 若表不存在，则创建表
        try
        {
            await Connection.CreateTableAsync<Item>(); // 创建表
            return 1;
        }
        catch (Exception)
        { // 创建表失败
            return -1;
        }
    }

    public async Task<int> InsertOne(Item item)
    {
        return await Connection.InsertAsync(item);
    }

    public async Task<int> InsertAll(List<Item> list)
    {
        return await Connection.InsertAllAsync(list);
    }

}